import React from 'react';

import { connect } from '@/dva';

import { withRouter } from 'react-router';

import { Redirect } from 'react-router-dom';

const whitePaths = ['/user/login'];

@connect({
  user: (state) => state.user
})
class Authorization extends React.PureComponent<any> {
  componentDidMount() {
    if (this.isLogin) {
      this.props.commit('user/userInfo')
    }
  }

  get location() {
    return this.props.location;
  }

  get userInfo() {
    const {
      userInfo
    } = this.props.user;
    return userInfo || {};
  }

  get isLogin() {
    return !!this.userInfo._id;
  }

  get inWhitePage() {
    const {
      pathname
    } = this.location;
    return whitePaths.includes(pathname);
  }

  render() {
    const { children } = this.props;

    if (this.isLogin && this.inWhitePage) {
      return <Redirect to="/home/app"/>
    }

    if (!this.isLogin && !this.inWhitePage) {
      return <Redirect to="/user/login"/>
    }

    return children;
  }
}

export default withRouter(Authorization);
